package cn.school.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.school.mybatis.pojo.Subject;
import cn.school.mybatis.service.SubjectService;

/**
 * Servlet implementation class SubjectServlet
 */
@WebServlet("/subjectServlet")
public class SubjectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SubjectServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	SubjectService service = new SubjectService();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int pageSize = 10;
		int p = 1;
		try {
			p = Integer.parseInt(request.getParameter("p"));
		} catch (Exception e) {
		}
		int total = service.getTotal();
		// 总页数
		int pageTotal = (total - 1) / pageSize + 1;

		List<Subject> list = service.select(p, pageSize);
		// 定义一个对象Page
		Map<String, Object> page = new HashMap<>();
		page.put("pageTotal", pageTotal);
		page.put("datas", list);
		String sb = JSON.toJSONString(page);
		// // [{},{}]
//		StringBuilder sb = new StringBuilder();
//		sb.append("[");
//		for (int i = 0; i < list.size(); i++) {
//			Subject s = list.get(i);
//			sb.append("{");
//			sb.append("\"id\":" + s.getId());
//			sb.append(",\"subjectname\":\"" + s.getSubjectname() + "\"");
//			sb.append(",\"classhour\":" + s.getClasshour());
//			sb.append(",\"gradeid\":" + s.getGradeid());
//			sb.append("}");
//			if (i < list.size() - 1) {
//				sb.append(",");
//			}
//		}
//		sb.append("]");
		// 设响应头
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().print(sb);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
